from otherparty.common import run_hg, run_svn, run_hgtk, run_command
from dirstate.utils import *

logger = logging.getLogger(__name__)
debug = logger.debug

HSVG_TAG_PRE = r'svn.r'
def cleandir(d):
	for file in listfiles(d):
		os.remove(file)

def prettyPrintRoot():
	"""Muestra el root del repo mixto."""
	if '-v' in sys.argv:
		print 'Root dir: "'+getRoot()+'"'
	else:
		print '"'+getRoot()+'"'
		
def show(out=[]):
	for l in out:
		print l,

def getSvnRev():
	"""Obtiene ultimo nro de revision del repo svn."""
	out = run_svn(['log','--limit','1','-q',getSvnUrl()]).split('\n')
	aux = 0
	for l in out:
		if(aux == 1):
			return re.findall(r'r\d+|',l)[0][1:]
		aux = aux + 1
	out.close()
	raise Exception, 'not access to repo'

def commitSvn(comment='commit en svn',addremove=False):
	"""Hace un commit en svn solo de lo que cambio."""
	if(len(sys.argv) > 2):
		comment = sys.argv[-1]
	out = []
	if '-Am' in sys.argv or addremove:
		st = statusSvn()
		for l in st:
			if l =='UNK':
				for f in st['UNK']:
					print run_svn(['add',f])
			if l == 'DEL':
				for f in st['DEL']:
					print run_svn(['del',f])
	print run_svn(['ci','-m',comment]+ getIncludeFolders())

def prettyGetSvnStatusList():
	"""Lista de los archivos que cambiaron en el repo como para subirlos"""		
	for k, l in statusSvn().items():
		if '-v' in sys.argv:
			print MAP_UNDEC_ST[k] + ":\n" + '\n'.join(map(lambda x: '\t'+x,l))
		else:
			print k + ":\n" + '\n'.join(map(lambda x: '\t'+x,l))

def prettyUrl():
	"""Obtiene url base del repo SVN"""
	for f in sys.argv[2:]:
		print getSvnUrl(file=f)
	print getSvnUrl()

def prettyRevs():
	"""Muestra revision local y del repo"""
	print 'rev Local:',getSvnLocalRev()
	print 'rev Svn:',getSvnRev()
	
def upLastSynch():
	"""Vuelve a ultima synch"""
	tag = 'svn.r'+str(getSvnLocalRev())
	run_hg(['up',tag])
	print 'update a synch:',tag

def prettyUpSvnList():
	"""Lista los archivos modificados desde el repo"""
	aux = getSvnUpFiles()
	debug(aux)
	print ' '+'\n '.join(aux)

import cmds.synch, cmds.init

cmdDic ={
'ci,commit':commitSvn,	
'revs':prettyRevs,
'st,status':prettyGetSvnStatusList,
'uplist':prettyUpSvnList,
'url':prettyUrl,
'update,up':updateSvnRepo,
'r,root':prettyPrintRoot,
'sy,synch':cmds.synch.main,
'init':cmds.init.main,
'lsynch':upLastSynch}

def executeCmd():
	cmd = sys.argv[1]
	for k in cmdDic:
		if cmd in k.split(','):
			cmdDic[k]()
	
"""
	habria que probar el parser de opt para argumentos de entrada
	tambien ncurses
"""
if __name__ == '__main__':
	if '-debug' in sys.argv:
		logging.basicConfig(level=10)
	logger.debug(sys.argv)
	if len(sys.argv) > 1:
		cmd = sys.argv[1]
	if len(sys.argv) > 1 and len(filter(lambda x : cmd in x.split(','), cmdDic)) > 0:
		if 'init' != sys.argv[1]:
			if IS_HSVG_REPO:
				executeCmd()
			else:
				print '"'+os.path.abspath('.')+'"','not a HSVG repo!\nMust be svn and hg repo at the same time.'
		else:
			executeCmd()
	else:
		if len(sys.argv) > 1:
			print '"' + ' '.join(sys.argv[1:]) + '" its not a valid option.'
		print 'HSVG: Rich and mixed hg-svn client by Damian Noseda <dnoseda@gmail.com>\n'
		print 'Usage:',os.path.basename(__file__).split('.')[0],'[command]','[options]\n'
		print 'Commands:\n'
		for dic in cmdDic:
			print '',dic.ljust(10),cmdDic[dic].__doc__

